<?php

class IndexController extends Metis_Controller_Action
{
    
    public function indexAction()
    {
    }
    
    public function loginAction()
    {
    	if ($this->auth->hasIdentity()){
            $this->_redirector->gotoUrl('/index');
    		return;
    	}
    }
    
    public function loginprocessAction()
    {
        if ($this->auth->hasIdentity()){
            $this->render('alreadyLoggedIn');
            return;
        }
        
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter());
        $authAdapter->setTableName('User')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password_sha1')
                    ->setCredentialTreatment('SHA1(?)');
                     
		$authAdapter->setIdentity($this->_getParam('login'))
		            ->setCredential($this->_getParam('password'));
		
		// Perform the authentication query, saving the result
		$result = $authAdapter->authenticate();
		
		if (!$result->isValid()){
		    $this->_redirector->gotoUrl('/index/index/login');
		}
		
		$this->auth->getStorage()->write($authAdapter->getResultRowObject(null, 'password'));
        
        $failedLogin = new Zend_Session_Namespace('failedLogin');
        if (isset($failedLogin->redirect)){
            $this->_redirector->gotoUrl($failedLogin->redirect);
        }
		
        $this->_redirector->gotoUrl('/index');
    }
    
    public function logoutAction()
    {
    	$this->auth->clearIdentity();
        $this->_redirector->gotoUrl('/index');
    }

    public function noRouteAction()
    {
        $this->_redirect('/');
    }
}
